import os
import django
import datetime
from django.utils import timezone
from django.contrib.auth.hashers import make_password

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'airshow_web.settings')
django.setup()

# 导入连接
from django.db import connection

def create_superuser(username, email, password):
    # 获取当前时间
    now = timezone.now().strftime('%Y-%m-%d %H:%M:%S')
    
    # 检查auth_user表是否存在
    with connection.cursor() as cursor:
        cursor.execute("SHOW TABLES LIKE 'auth_user'")
        if not cursor.fetchone():
            # 创建auth_user表
            cursor.execute("""
            CREATE TABLE IF NOT EXISTS `auth_user` (
              `id` int NOT NULL AUTO_INCREMENT,
              `password` varchar(128) NOT NULL,
              `last_login` datetime(6) DEFAULT NULL,
              `is_superuser` tinyint(1) NOT NULL,
              `username` varchar(150) NOT NULL,
              `first_name` varchar(150) NOT NULL,
              `last_name` varchar(150) NOT NULL,
              `email` varchar(254) NOT NULL,
              `is_staff` tinyint(1) NOT NULL,
              `is_active` tinyint(1) NOT NULL,
              `date_joined` datetime(6) NOT NULL,
              PRIMARY KEY (`id`),
              UNIQUE KEY `username` (`username`)
            )
            """)
    
    # 哈希密码
    hashed_password = make_password(password)
    
    # 检查用户是否已存在
    with connection.cursor() as cursor:
        cursor.execute("SELECT id FROM auth_user WHERE username = %s", [username])
        user = cursor.fetchone()
        
        if user:
            # 更新现有用户
            cursor.execute("""
            UPDATE auth_user SET 
                password = %s,
                is_superuser = 1,
                email = %s,
                is_staff = 1,
                is_active = 1
            WHERE username = %s
            """, [hashed_password, email, username])
            print(f"超级用户 {username} 已更新")
        else:
            # 创建新用户
            cursor.execute("""
            INSERT INTO auth_user (
                password, 
                last_login,
                is_superuser, 
                username, 
                first_name, 
                last_name, 
                email, 
                is_staff, 
                is_active, 
                date_joined
            ) VALUES (%s, %s, 1, %s, '', '', %s, 1, 1, %s)
            """, [hashed_password, now, username, email, now])
            print(f"超级用户 {username} 已创建")

if __name__ == '__main__':
    # 创建超级用户
    create_superuser('admin', 'admin@example.com', 'admin123456') 